
$(function(){

    var BaseList =  $("#order-ul-list");
    var ListDesc =  $("#list-desc");
    var inputOrder = $("#input-order");
    var totalAll  = $("#totalAll");
    var payAll    = $("#payAll");
    var expressAll = $("#expressAll");
    var redbag    =  $("#red-bag");
    var redbag_layer = $("#red-bag-layer");
    var redInfo = $("#redInfo");
    $('.payType .radioItem').click(function(){
    	var me = $(this);
    	if(me.hasClass('offline')){
    		$('.promption-info').empty().hide();
    	}
    });
    //出始化spinner
    $(".spi").spinner({});

    //重新计算价格
    $(".spi").on("spin",function(e,ui){

        var $this = $(this);
        var value = ui.value;
        if(value < 0){
            //console.log("<=0");
            return false;
        };
        var total = 0;
        var base = $this.closest("ul");
        if(value == "" || value <=0){
            value = 0;
        }
         total = calclTotl(value,base.find(".order-price span").html()).toFixed(2);
         base.find(".order-total span").html(total);

        //总价格变动
        calcTotalAll();

    });

    //修改地址操作
    $(".address-list-update").on("click",function(){
    	var $this = $(this);
        var parent = $(this).closest("li");
        parent.find(".address-title").hide();
        parent.find(".address-input").show();
        $(".address-list-ul a[name=address],.address-add a[name=address]").removeClass('radioChecked');
        parent.find("a[name=address]").addClass("radioChecked");
        if(!parent.hasClass('checked')){
        	parent.addClass('checked');
        	if(parent.siblings('li').length>0){        		
        		parent.siblings('li').removeClass('checked');
        	}
        }
        var other = parent.siblings();
        other.find(".address-title").show();
        other.find(".address-input").hide();

         if( $(".address-add").is(":visible")){
              $(".address-add").hide();
         }
       
    });

    //订单备注
    ListDesc.on("click","li",function(){
        var value = inputOrder.val();
        var t = $(this).text();
        
        var reg = new RegExp();
		switch(t) {
			case "不要辣":
				reg = /\u4e0d\u8981\u8fa3/;
				break;
			case "多加米":
				reg = /\u591a\u52a0\u7c73/;
				break;
			case "不要蒜":
				reg = /\u4e0d\u8981\u849c/;
				break;
			case "不要香菜":
				reg = /\u4e0d\u8981\u9999\u83dc/;
				break;
		}
		if(reg.test(value)) {
			 return;
		}else {
			 if($.trim(value) == "") {
	            inputOrder.val($.trim($(this).html()));
			 } else {
	            inputOrder.val(value + " " + $.trim($(this).html()));
			 }
		 }
    });
    var calclTotl = function(num,price){
        return parseInt(num) * parseFloat(price);
    };

    var calcTotalAll = function(){
        var   sps = BaseList.find(".order-menu").find(".order-total span");
        var res = 0;
        for(var i =0; i <sps.length ;i++){
            res+=parseFloat($(sps[i]).html());
        }
        totalAll.html(res);
        var express =  parseFloat(expressAll.html());
        payAll.html(express + res);
    };
    //红包显示
    $("#red-bag").click(function(){
         var ck = this.checked;
        if(ck){
            redbag_layer.css("display","inline");
            $(".getSource").css({"position":"relative", "top":"-25px"});
            redInfo.show();
        }
        else{
            $(".getSource").css({"position":"relative", "top":"0px"});
            redbag_layer.hide();
            redInfo.hide();
        }
    });
    //切换隐藏层
    var toggleLayer = function(tg){
        if(tg == true){
            $("#mask").show();
            $("#addressLayer").show();
        }	
        else{
            $("#mask").hide();
            $("#addressLayer").hide();
        }
    };
    addressManage.init();
});


var addressManage = {};
addressManage.inputAddressFlag = false;
addressManage.editAddressFlag = false;
addressManage.currentAddress = null;

var selectedAddrId = null;

addressManage.init = function() {
     //修改地址
	
	require_template('addressList')
    require_template('singleAddress')

    addressManage.reload();


     $("#updateAddress").click(function(){
        toggleLayer(true);
     });
     
     //根据cookie初始化地址
     if($.cookie('currentInputAddress')) {
    	 $("#currentInputAddress").val($.cookie('currentInputAddress'));
     }
     if($.cookie('currentInputTel')) {
    	 $("#currentInputTel").val($.cookie('currentInputTel'));
     }
     if($.cookie('currentInputShortTel')) {
    	 $("#currentInputShortTel").val($.cookie('currentInputShortTel'));
     }
     jQuery('input[placeholder]').placeholder();
}


addressManage.list = function() {
    var templateStr = $('#template_addressList').html();
    return AuiAjax("/mvc/address/list", null, function(res){return _.template(templateStr,{data : res.data})}, null, null);
}


addressManage.add = function(address, tel, shortTel, successCallback, errorCallback) {
    return AuiAjax("/mvc/address/add",{addr : address, contactPhone:tel, contactShortPhone:shortTel }, successCallback, null, errorCallback);
}

addressManage.update = function(addrId, address, tel, shortTel) {
    return AuiAjax("/mvc/address/update",{addressId:addrId, addr : address, contactPhone:tel, contactShortPhone:shortTel }, null, null, null);
}

addressManage.remove = function(addrId) {
    return AuiAjax("/mvc/address/remove", {addressId:addrId}, null, null, null);
}

addressManage.reload = function() {
    $('#addressForm .address-list-ul').html(this.list());
    addressManage.rebind();
    $('.address-list-ul a[name=address]').eq(0).addClass('radioChecked');
    $('.address-list-ul li').eq(0).addClass('checked')
    if($('.address-add').css('display')=='none'){
    	addressManage.setbg(2)
    }else{
    	addressManage.setbg(1)
    }
    
}

addressManage.selectCurrentAddress = function() {

    if(addressManage.currentAddress != null) {
        $('.address-list-ul a[name=address]').removeClass('radioChecked');
        $('.address-list-ul a[name=address]').addClass('radioChecked');
    } else {
        var radios = $('.address-list-ul .address-add input');


    }
}
addressManage.setbg = function(args){
	$(".address-list-ul>li").each(function(index,item){
		$(item).hasClass('bgf3')?$(item).removeClass('bgf3'):'';
		$(item).hasClass('bgff')?$(item).removeClass('bgff'):'';
		if((index%2)==0){
			if(args==1){
				$(item).addClass('bgff');
			}else{
				$(item).addClass('bgf3');
			}
		}else{
			if(args==1){
				$(item).addClass('bgf3');
			}else{
				$(item).addClass('bgff');
			}
		}
	 });
}
addressManage.rebind = function() {
	function bindfocus(){
		$(".address-list-ul, .address-add").find(".borderff6931").focus(function(){
			$("#errorTip").html('');
			$(".borderff6931").removeClass('borderff6931');
		});
	}
	$(".address-list-ul, .address-add").find(".borderff6931").focus(function(){
		$("#errorTip").html('');
	});
    $("#addAddress").click(function(){
        //clear选中状态
        var parent = $(".address-list-ul").find("li");
        parent.find(".address-title").show();
        parent.find(".address-input").hide();
        $('.address-list-ul a[name=address]').removeClass('radioChecked');
        $(".address-add").show().find("[name='address']").addClass('radioChecked');
        
        if(!$('.address-add').find('li').hasClass('checked')){
        	$('.address-add').find('li').addClass('checked');
        	if($(".address-list-ul").find("li").length>0){        		
        		$(".address-list-ul").find("li").removeClass('checked');	
        	}
        }
        if( $(".address-list-ul, .address-add").find("a.radioChecked").length==0){
			$(".address-list-ul a[name=address]").eq(0).addClass('radioChecked');
        }
        addressManage.setbg(1);

        addressManage.inputAddressFlag = true;
        addressManage.editAddressFlag = false;
    });

    $('.address-list-update').on("click",function(){
         var $this = $(this);
        var parent = $(this).closest("li");
        parent.find(".address-title").hide();
        parent.find(".address-input").show();
        $(".address-list-ul a[name=address],.address-add a[name=address]").removeClass('radioChecked');
        parent.find("a[name=address]").addClass("radioChecked");
        if(!parent.hasClass('checked')){
        	parent.addClass('checked');
        	if(parent.siblings('li').length>0){        		
        		parent.siblings('li').removeClass('checked');
        	}
        }
        var other = parent.siblings();
        other.find(".address-title").show();
        other.find(".address-input").hide();

        if( $(".address-add").is(":visible")){
          $(".address-add").hide();
        }

        addressManage.editAddressFlag = true;
        return false;
    });
    
    $('.address-list-cancel').click(function(){
    	$(".address-add input").val('');
    	$(".address-add").find("a[name=address]").removeClass('radioChecked');
    	$(".address-list-ul a[name=address]").eq(0).addClass('radioChecked');
    	$(".address-add").hide();
    });
     //删除
	 $('.address-list-delete').on("click", function() {
		var parent = $(this).closest("li");

		$("#errorTip").html('');
		var addrId = parent.find('a[name=address]').attr('addrId');

		if(addrId!=undefined){
			addressManage.remove(addrId);
		}else{
			//$(this).closest("ul").hide();
			if($(".address-list-ul").find('li').length==0){
				toggleLayer(false);
			}else{
				addressManage.setbg(2);
			}
			 if( $(".address-add").is(":visible")){
				 if( $(".address-list-ul").find("a.radioChecked").length==0){
						$(".address-list-ul a[name=address]").eq(0).addClass('radioChecked');
				 	}
		          $(".address-add").hide();
		      }
			return false;
		}
		var preParent = parent.parent();
		parent.remove();
		addressManage.setbg(2);
		if( $(".address-list-ul, .address-add").find("a.radioChecked").length==0){
				$(".address-list-ul a[name=address]").eq(0).addClass('radioChecked');
		}
		//处理地址全部删除完的情况
		if(preParent.find("li").size()<=0) {
			//触发添加地址的事件
			$("#addAddress").trigger("click");
			//浮层背后的地址清空
			$("#inputAddress").remove();
			$("#selectedAddress").find("div").css("display","block").hide();
			$("#selectedAddress").append("<a class='info_a'><div><span class='block fl room-title p17 f-16' style='cursor: default;'>收餐地址 </span><input id='currentInputAddress' type='text' class='room-input' name='address' placeholder='输入收餐地址' style='top: 7px;font-size: 14px;line-height:31px;'><span class='fc-ff6931 sginstar'>*</span><div class='tips' style='margin: 10px 0 0px 0;text-indent: 0px;color: #FF3B30;cursor: default;'></div></div><div><span class='block fl room-title p17 f-16' style='cursor: default;'>收餐电话</span><input id='currentInputTel' type='text' style='width:145px;top: 7px;font-size: 14px;line-height:31px;' class='room-input tel' name='tel' placeholder='输入手机号'><span class='fc-ff6931 sginstar'>*</span><input id='currentInputShortTel' type='text' class='room-input shortTel' name='shortTel' style='font-size: 14px;width:124px;margin-left: 4px;top: 7px;line-height:31px;' placeholder='固话或短号(选填)'><div class='tips_phone' style='cursor: default;'></div></div></a>");

			jQuery('input[placeholder]').placeholder();
			toggleLayer(false);
		}
	 });
    
    // 弹出层关闭
    $(".mask").click(function(){
        toggleLayer(false);
    });

    //取消
    $("#cancelbtn").click(function(){
    	$(".address-add").hide().find("[name='address']").removeClass('radioChecked');
    	$(".address-add").find('input[type=text]').val('');
        $("#errorTip").html('');
        if( $(".address-list-ul, .address-add").find("a.radioChecked").length==0){
			$(".address-list-ul a[name=address]").eq(0).addClass('radioChecked');
		}
        toggleLayer(false);
    });


    $('.address-list-ul li').on('click', function(e) {
        //clear选中状态
    	var event = e || window.event;
    	var tagName = (event.target || event.srcElement).tagName.toUpperCase();
    	var name = event.target.getAttribute('name');
    	
    	if((event.target || event.srcElement) == this || tagName == 'SPAN' ||(tagName=="A"&&name=='address')){
    	//var type = event.target.getAttribute('type')||'ss';
    	//if((event.target || event.srcElement) == this || tagName == 'SPAN' ||(tagName=="A"&&type=='radio')){
	        var parent = $(".address-list-ul").find("li");
	        parent.find(".address-title").show();
	        parent.find(".address-input").hide();
	
	        //切换单选按钮时，隐藏掉新增地址输入框
	        var inputParent = $(".list-unstyled.address-add");
	        inputParent.hide();
	        inputParent.find('input[name=addressAli]').val("");
	        inputParent.find('input[name=phoneNum]').val("");
	        inputParent.find('input[name=shortNum]').val("");
	        $("#errorTip").html("");
	        addressManage.inputAddressFlag = false;
	        addressManage.editAddressFlag = false;
	        $('ul.address-list-ul,ul.address-add').find('a[name=address]').removeClass('radioChecked');
	        $(this).find('a[name="address"]').addClass('radioChecked');
//	        $(this).find('input[name="address"]').attr("checked", "checked").attr("value", 1);
	        if(!$(this).hasClass('checked')){
	        	$(this).addClass('checked');
	        	if($(this).siblings('li').length>0){
	        		$(this).siblings('li').removeClass('checked');
	        	}
	        	 addressManage.setbg(2);
	        }
    	}
    });
   


      //保存
    $("#savebtn").click(function(){

        if(addressManage.inputAddressFlag == true) {
            var parent = $('.address-add li').eq(0);

            //缺少校验
            var address = parent.find('input[name=addressAli]').val();
            var tel = parent.find('input[name=phoneNum]').val();
            var shortTel = parent.find('input[name=shortNum]').val();
            
            //添加校验
            if(address == undefined || trim(address)=="") {
            	$("#errorTip").html("&nbsp;&nbsp;&nbsp;*地址不能为空哦");
            	parent.find('input[name=addressAli]').addClass('borderff6931');
            	bindfocus();
            	return;
            }
            
            
            if(address.length > 100){
            	$("#errorTip").html("&nbsp;&nbsp;&nbsp;*地址过长，请重新输入");
            	parent.find('input[name=addressAli]').addClass('borderff6931');
            	bindfocus();
            	return;
            }
            parent.find('input[name=addressAli]').removeClass('borderff6931');	
            if(tel == undefined || trim(tel)=="") {
            	$("#errorTip").html("&nbsp;&nbsp;&nbsp;*号码不能为空哦");
            	parent.find('input[name=phoneNum]').addClass('borderff6931');
            	bindfocus();
            	return;
            }
             parent.find('input[name=phoneNum]').removeClass('borderff6931');
            if(!tel.match( /^\d{11}$/ )){
            	$("#errorTip").html("&nbsp;&nbsp;&nbsp;*号码格式有误哦");
            	parent.find('input[name=phoneNum]').addClass('borderff6931');
            	bindfocus();
                return true;
            }
             parent.find('input[name=phoneNum]').removeClass('borderff6931');
            /*
            if(shortTel != undefined && trim(shortTel)!="" && !shortTel.match( /^((\d{3,4})-)?(\d{6,8})/ )){
            	$("#errorTip").html("短号格式有误哦");
                return true;
            }*/
            $("#errorTip").html("");
            var addStatus = false;
            addressManage.add(address, tel, shortTel, function(result){
            	addStatus = true;
                $('.address-list-ul').prepend(_.template($('#template_singleAddress').html(), {item : result.data}));
                $('.address-list-ul a[name=address],.address-add a[name=address]').removeClass('radioChecked');
                $('.address-list-ul a[addrid=' + result.data.id + ']').addClass('radioChecked');
                var parent = $('.address-list-ul input[addrid=' + result.data.id + ']').closest('li');
                if(!parent.hasClass('checked')){
					parent.addClass('checked');
					if(parent.siblings('li').length>0){        		
						parent.siblings('li').removeClass('checked');
					}
				}
                $('.address-add').hide();
                addressManage.setbg(2);
            }, function() {
            	alert("新增地址失败");
            });
            if(!addStatus){
            	return;
            }
            
            addressManage.inputAddressFlag = false;
            parent.find('input[name=addressAli]').val("");
            parent.find('input[name=phoneNum]').val("");
            parent.find('input[name=shortNum]').val("");
            
            //处理清空地址后，再添加地址的情况
            $("#inputAddress").remove();
            $("#selectedAddress").find("div").css("display","none").show();
            
        }

        var ckdom = $(".address-list-ul, .address-add").find("a.radioChecked");
        if(ckdom.length==0){
        	ckdom = $(".address-list-ul").find("a[name=address]").eq(0);
        }

        var addressId = ckdom.attr('addrid');
        selectedAddrId = addressId;
        var temp = ckdom.parent();

        var address  = $.trim(temp.find("[name='addressAli']").val());
        var telephone  =  $.trim(temp.find("[name='phoneNum']").val());
        var shortTelephone  =  $.trim(temp.find("[name='shortNum']").val());

        if(addressManage.editAddressFlag == true) {
        	//$("#errorTipEdit").remove();
        	//temp.find("div.address-input").append("<span id='errorTipEdit' class='room-input-errorTip'></span>");
            //添加校验
        	 //添加校验
            
            if(address == undefined || address=="") {
            	$("#errorTip").html("&nbsp;&nbsp;&nbsp;*地址不能为空哦");
            	temp.find('input[name=addressAli]').addClass('borderff6931');
            	bindfocus();
            	return;
            }
            
            if(address.length > 100){
            	$("#errorTip").html("&nbsp;&nbsp;&nbsp;*地址过长，请重新输入");
            	temp.find('input[name=addressAli]').addClass('borderff6931');
            	bindfocus();
            	return;
            }
            temp.find('input[name=addressAli]').removeClass('borderff6931');	
            if(telephone == undefined || telephone=="") {
            	$("#errorTip").html("&nbsp;&nbsp;&nbsp;*号码不能为空哦");
            	temp.find('input[name=phoneNum]').addClass('borderff6931');
            	bindfocus();
            	return;
            }
            
            if(!telephone.match( /^\d{11}$/ )){
            	$("#errorTip").html("&nbsp;&nbsp;&nbsp;*号码格式有误哦");
            	temp.find('input[name=phoneNum]').addClass('borderff6931');
            	bindfocus();
                return true;
            }
            temp.find('input[name=phoneNum]').removeClass('borderff6931');
            if(addressManage.update(addressId, address, telephone, shortTelephone)) {

                temp.find('.address-title span').eq(0).html(address);
                temp.find('.address-title span').eq(1).html(telephone + " " + shortTelephone);
                addressManage.setbg(2);
            } else {
                alert('修改地址失败');
                return;
            }
            
        } 

        $('#curAddress').html(address);
        $('#curAddress').attr('title',address);
        $('#curTel').html(telephone);
        $('#curTel').attr('title',telephone);
        $('#curShortTel').html(shortTelephone);
        $('#curShortTel').attr('title',shortTelephone);
        addressManage.currentAddress = addressId;
        toggleLayer(false);

        addressManage.rebind();

    });

	$("#currentInputAddress").bind("propertychange input", function() {
		$.cookie('currentInputAddress', $("#currentInputAddress").val());
	});
	$("#currentInputTel").bind("propertychange input", function() {
		$.cookie('currentInputTel', $("#currentInputTel").val());
	});
	$("#currentInputShortTel").bind("propertychange input", function() {
		$.cookie('currentInputShortTel', $("#currentInputShortTel").val());
	});
}

function AuiAjax(url, data, successStatusCallback, errorStatusCallback, errorCallback) {

 var res;
 $.ajax({
    url : getRootPath() + url,
    cache : false, 
    async : false,
    type : "POST",
    dataType : 'json',
    data : data,

    success : function (result){      
        if(result.status == 'success') {
            if(typeof successStatusCallback === 'function') {
                res = successStatusCallback(result)
            } else {
                res = true;
            }
        } else {
           if(typeof errorStatusCallback === 'function') {
                res = errorStatusCallback(result)
           } else {
                res = false;
           }
        }
    },
    error   :   function(){
        if(typeof errorCallback === 'function') {
            res = errorCallback()
        } else {
            //console.log & //console.log('error');
        }
    }
});

return res;
}

//切换隐藏层
var toggleLayer = function(tg){
    if(tg == true){
        $("#mask").show();
        $("#addressLayer").show();
    }   
    else{
    	$('.address-list-ul a[name=address]').removeClass('radioChecked');
    	if(selectedAddrId != null) {
    		$('.address-list-ul a[addrid=' + selectedAddrId + ']').addClass('radioChecked');
    	} else {
    		$('.address-list-ul a[name=address]').eq(0).addClass('radioChecked');;
    	}
        $("#mask").hide();
        $("#addressLayer").hide();
    }
};



